using System;
using System.Collections.Generic;
using Castle.ActiveRecord;

namespace Scrummer.Models
{
	[ActiveRecord]
	public class Sprint : AbstractModel<Sprint>
	{
		private string name;
		private Project project;
		private Backlog backlog;
		private int targetEstimate;
		private Status status = Status.Blank;
		private DateTime startDate = DateTime.Today;
		private DateTime endDate = DateTime.Today.AddMonths(1);

		public Sprint()
		{
			backlog = new Backlog();
		}

		[Property]
		public string Name
		{
			get { return name; }
			set { name = value; }
		}

		[BelongsTo]
		public Project Project
		{
			get { return project; }
			set{project = value;}
		}

		[Property]
		public int TargetEstimate
		{
			get { return targetEstimate; }
			set { targetEstimate = value; }
		}

		[BelongsTo]
		public Backlog Backlog
		{
			get { return backlog; }
			protected set { backlog = value; }
		}

		[Property]
		public DateTime StartDate
		{
			get { return startDate; }
			set { startDate = value; }
		}

		[Property]
		public DateTime EndDate
		{
			get { return endDate; }
			set { endDate = value; }
		}

		[Property]
		public string StatusString
		{
			get { return status.Name; }
			protected set { status = Status.Decode(value); }
		}

		public Status Status
		{
			get { return status; }
			set { status = value; }
		}

		public double Estimate
		{
			get { return backlog.Estimate; }
		}

		public double DetailEstimate
		{
			get { return backlog.DetailEstimate; }
		}

		public double Effort
		{
			get { return backlog.Effort; }
		}

		public double EffortRemaining
		{
			get { return backlog.EffortRemaining; }
		}

		public static IList<Sprint> FindAll(int projectId)
		{
			return Project.Find(projectId).Sprints;
		}

		public void AddWorkItem(WorkItem workItem)
		{
			if (backlog == null)
				backlog = new Backlog();

			backlog.Add(workItem);
		}

		protected override void OnSaving()
		{
			if(backlog != null && backlog.IsNew)
				backlog.Create();
			else if (backlog != null)
				backlog.Save();

			base.OnSave();
		}

		protected override void OnCreating()
		{
			if (backlog != null && backlog.IsNew)
				Backlog.Create();
	
			base.OnCreating();
		}
	}
}